package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;

import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void sendVerifyCode(String phone, String code) {
        String key = RedisKeys.VERIFY_CODE.join(phone);
        //设置key和value有效存储为5分钟
        template.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        //生成key
        String key = RedisKeys.VERIFY_CODE.join(phone);
        //根据key获取值
        String code = template.opsForValue().get(key);
        return code;
    }

    @Override
    public void setLoginToken(String token, UserInfo user) {
        //生成key
        String key = RedisKeys.LOGIN_TOKEN.join(token);
        //将user转为json格式
        String userString = JSON.toJSONString(user);
        //存储到redis中,有效时间为30分钟
        template.opsForValue().set(key, userString, RedisKeys.LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public UserInfo getUserInfoToToken(String token) {
        //对参数进行判空
        AssertUtil.haslength(token, "请先登录");
        //根据token生成key
        String key = RedisKeys.LOGIN_TOKEN.join(token);
        //判断是否存在key
        if (!template.hasKey(key)) {
            return null;
        }
        //根据key来查询
        String userString = template.opsForValue().get(key);
        //判断是否为空
        AssertUtil.haslength(userString, "登录失效");
        //将userString转为对象
        UserInfo user = JSON.parseObject(userString, UserInfo.class);

        return user;
    }

    @Override
    public List<String> favor(String sid, String userId) {
        String key = RedisKeys.USER_FAVOR.join(userId);
        List<String> ids = new ArrayList<>();
        if (template.hasKey(key)){
            String str = template.opsForValue().get(key);
            ids = JSON.parseArray(str, String.class);
        }
        return ids;
    }
}
